package com.hee.erp.modules.service.impl;

import com.hee.erp.modules.entity.SysCompany;
import com.hee.erp.modules.entity.SysDepart;
import com.hee.erp.modules.mapper.SysCompanyMapper;
import com.hee.erp.modules.service.ISysCompanyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hee.erp.modules.service.ISysDepartService;
import com.hee.erp.vo.ZTreeNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author weizehong
 * @since 2022-04-15
 */
@Service
@Transactional
public class SysCompanyServiceImpl extends ServiceImpl<SysCompanyMapper, SysCompany> implements ISysCompanyService {

    @Autowired
    ISysDepartService sysDepartService;

    @Override
    public List<ZTreeNode> getTreeNodes() {

        //读取所有公司
        List<SysCompany> companyList = this.list();
        //读取所有部门
        List<SysDepart> departList = sysDepartService.list();

        List<ZTreeNode> zTreeNodeList = companyList.stream().map(company -> {
            //构建公司节点
            ZTreeNode companyNode = new ZTreeNode();
            companyNode.setId(company.getId());
            companyNode.setName(company.getCompanyName());
            companyNode.setPId("0");
            companyNode.setOpen(true);
            companyNode.setIsParent(true);
            companyNode.setType("company");
            return companyNode;

        }).collect(Collectors.toList());

        for (ZTreeNode zTreeNode : zTreeNodeList) {
            List<ZTreeNode> children = departList.stream().filter(depart -> depart.getCompanyId().equals(zTreeNode.getId())).map(depart -> {
                //构建部门节点
                ZTreeNode departNode = new ZTreeNode();
                departNode.setId(depart.getId());
                departNode.setName(depart.getDepartName());
                departNode.setPId(zTreeNode.getId());
                departNode.setIsParent(false);
                departNode.setType("depart");
                return departNode;
            }).collect(Collectors.toList());
            zTreeNode.setChildren(children);
        }

        return zTreeNodeList;

    }
}
